<!--
 * @Descripttion: 
 * @LastEditors: xzh
 * @LastEditTime: 2024-06-10 15:42:50
-->
<template>
  <teleport to="#selectItem-select-container" :disabled="!appendToBody">
    <DileLayer
      v-model="selectItemParam.visible"
      :layerWidth="layerWidth"
      :layerHeight="layerHeight"
      :title="`${$t('common.selectArr.select')}${$t(
        selectTableTypeLabel[selectTableType] || 'common.selectArr.object'
      )}`"
      @sure="handleSure"
      @close="selectItemParam.visible = false"
    >
      <div class="selectItem-table">
        <!-- 搜索工具类 -->
        <SearchTools
          :selectTableType="selectTableType"
          @search="initTableData"
        />
        <!-- 选择对象表格 -->
        <DileTable class="relEquip-table" ref="dileTableRef">
          <template #preColumn>
            <vxe-column
              v-for="column in SelectTableUtils.tableColumnMap[selectTableType]"
              :key="column.field"
              :field="column.field"
              :title="$t(column.title)"
            >
              <template #default="{ row }">
                <!-- 格式化表格 -->
                <span>{{
                  SelectTableUtils.formatColumn(selectTableType, row, column)
                }}</span>
              </template>
            </vxe-column>
          </template>
        </DileTable>
      </div>
    </DileLayer>
  </teleport>
</template>

<script setup lang="ts">
import { object_Inf } from "@/utils/typings/index.type";
import { ref, reactive, provide, nextTick } from "vue";
import { propsParam_Inf } from "@/components/dile-table/index.type";
import { selectTableTypeEnum, selectTableTypeLabel } from "../index.type";
import Dile_APi from "@/api";
import DileTable from "@/components/dile-table/index.vue";
import DileLayer from "@/components/dile-layer/index.vue";
import SelectTableUtils from "./utils";
import SearchTools from "./selectItem-searchTools/index.vue";

const emit = defineEmits(["sure"]);

const props = defineProps({
  //选择列表类型
  selectTableType: {
    type: String,
    requited: true,
    default: "",
  },
  //多选
  multiple: {
    type: Boolean,
    requited: false,
    default: true,
  },
  //自身是否插入至 body
  appendToBody: {
    type: Boolean,
    requited: false,
    default: true,
  },
  //定义弹窗宽度
  layerWidth: {
    type: [Number, String],
    requited: false,
    default: 1000,
  },
  //定义弹窗高度
  layerHeight: {
    type: [Number, String],
    requited: false,
    default: 600,
  },
  //选择keys
  selectedKeys: {
    type: Array<Number>,
    requited: false,
    default: [],
  },
});

/**
 * @Author: xzh
 * @Descripttion: 表格实例
 * @Param:
 */
let dileTableRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion: 选择对象参数
 * @Param:
 */
let selectItemParam = reactive<object_Inf>({
  visible: false,
});

/**
 * @Author: xzh
 * @Descripttion: 初始化
 * @Param:
 */
let init = async () => {
  try {
    propsParam.loading = true;
    //打开弹框
    Object.assign(selectItemParam, {
      visible: true,
    });
    await nextTick();
    //加载表格
    await initTableData();
  } finally {
    propsParam.loading = false;
  }
};

/**
 * @Author: xzh
 * @Descripttion: 加载表格
 * @Param:
 */
let initTableData = async (searchParam: Object = {}) => {
  let { selectTableType, selectedKeys } = props,
    { page, rows } = dileTableRef.value?.getTableParam()?.pagination || {},
    tableData: object_Inf = {};
  //根据选择对象类型加载数据源
  switch (selectTableType) {
    case selectTableTypeEnum.equip:
      //加载设备
      tableData = await Dile_APi.getEquipArchivesList({
        keyWord: "",
        ...searchParam,
        pagination: {
          pageIndex: page,
          pageSize: rows,
        },
      });
      break;
    case selectTableTypeEnum.equipUpkeepItem:
      //加载设备保养项目
      tableData = await Dile_APi.getEquipUpkeepItemList({
        keyWord: "",
        ...searchParam,
        pagination: {
          pageIndex: page,
          pageSize: rows,
        },
      });
      break;
    case selectTableTypeEnum.mold:
      //加载模具
      tableData = await Dile_APi.getMoldArchivesList({
        keyWord: "",
        ...searchParam,
        pagination: {
          pageIndex: page,
          pageSize: rows,
        },
      });
      break;
    case selectTableTypeEnum.moldUpkeepItem:
      //加载模具保养项目
      tableData = await Dile_APi.getMoldUpkeepItemList({
        keyWord: "",
        ...searchParam,
        pagination: {
          pageIndex: page,
          pageSize: rows,
        },
      });
      break;
  }
  let { record, total } = tableData;

  Object.assign(propsParam, {
    tableData: record,
    tableRecords: total,
  });
  await nextTick();
  //设置行选中
  selectedKeys.length > 0 && setTableSelected();
};

/**
 * @Author: xzh
 * @Description: 设置行选中
 * @Param:
 */
let setTableSelected = () => {
  let { selectedKeys } = props,
    { tableData, rowConfig = {} }: propsParam_Inf | object_Inf =
      propsParam || {},
    { setCheckboxRow = () => {} } = dileTableRef.value;
  //获取已选数据
  let selectedRowArr =
    tableData?.filter(
      (x: object_Inf) => !!selectedKeys.includes(x[rowConfig.keyField || "id"])
    ) || [];
  //设置行选中
  selectedRowArr?.length > 0 && setCheckboxRow(selectedRowArr, true);
};

/**
 * @Author: xzh
 * @Descripttion: 确定事件
 * @Param:
 */
let handleSure = () => {
  let { rowChecked, getTableParam } = dileTableRef.value;
  if (!rowChecked()) {
    return false;
  }
  //获取表格选择项
  let { selectObjArr } = getTableParam();
  //触发回调
  emit("sure", selectObjArr);
  //关闭弹框
  selectItemParam.visible = false;
};

/**
 * @Author: xzh
 * @Descripttion: 表格参数
 * @Param:
 */
let propsParam = reactive<propsParam_Inf>({
  loading: false,
  //多选/单选
  checkbox: !!props.multiple,
  radio: !props.multiple,
  tableData: [],
  isPagination: true,
  emitEvents: {
    refreshTable: initTableData,
  },
});
provide("propsParam", propsParam);

defineExpose({
  init,
});
</script>
<style lang="scss" scoped>
.selectItem-table {
  display: flex;
  flex-direction: column;
  flex: 1;
  height: 0;
  overflow: auto;
  padding: 1rem;
  gap: 1rem;
  .relEquip-table {
    flex: 1;
    height: 0;
  }
}
</style>
